﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EntityFramework.Extensions;

namespace DAO
{
    public class RoomRequestDAO
    {
        WebChatDBEntities db = new WebChatDBEntities();

        public RoomRequest GetRoomRequest(int userId)
        {
            var request = db.RoomRequests.FirstOrDefault(r => r.ToUserId == userId);
            return request;
        }

        public bool AddRoomRequest(int userId, string friendName, int roomId)
        {
            User friend = db.Users.SingleOrDefault(u => u.UserName.Equals(friendName));
            if (friend == null)
                return false;

            RoomRequest request = new RoomRequest
                                  {
                                      UserId = userId,
                                      ToUserId = friend.Id,
                                      RoomId = roomId
                                  };

            db.RoomRequests.Add(request);
            db.SaveChanges();
            return true;
        }

        public bool DeleteRoomRequest(int userId, int roomId)
        {
            RoomRequest request = db.RoomRequests.FirstOrDefault(r => r.RoomId == roomId && r.ToUserId == userId);
            if(request == null)
                return false;

            db.RoomRequests.Remove(request);
            db.SaveChanges();
            return true;
        }

        public void DeleteAllRequestsOfOneRoom(int roomId)
        {
            db.RoomRequests.Delete(r => r.RoomId == roomId);
            
            db.SaveChanges();
        }

        public void DeleteAllRequestsOfOneUser(int userId)
        {
            db.RoomRequests.Delete(r => r.UserId == userId || r.ToUserId == userId);
            db.SaveChanges();
        }
    }
}
